<template>
  <s-clean-layout :title="isAdd ? '添加借钱记录' : '编辑借钱记录'" navbar="normal">
    <view class="borrow-edit-container">
      <!-- 表单内容 -->
      <view class="form-container">
        <!-- 联系人 -->
        <view class="form-item contact-item" @tap="selectContact">
          <template v-if="formData.contactId">
            <view class="avatar-container">
              <image v-if="formData.contactImg" class="avatar" :src="formData.contactImg" mode="aspectFill"></image>
              <view v-else class="avatar-placeholder">
                <text>{{ getNameInitial(formData.contactName) }}</text>
              </view>
            </view>
            <text class="contact-name">{{ formData.contactName }}</text>
          </template>
          <template v-else>
            <text class="contact-add">点击添加联系人</text>
          </template>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 事项名称 -->
        <view class="form-item">
          <view class="form-label">事项名称</view>
          <view class="item-value">
            <input
              v-model="formData.eventName"
              placeholder="请输入事项名称"
              class="input-field"
            />
          </view>
        </view>
        
        <!-- 类型选择 -->
        <view class="form-item">
          <view class="form-label">类型</view>
          <view class="type-selector">
            <view 
              class="type-item" 
              :class="{ active: formData.transactionType === 'OUT' }"
              @tap="formData.transactionType = 'OUT'"
            >
              借出
            </view>
            <view 
              class="type-item" 
              :class="{ active: formData.transactionType === 'IN' }"
              @tap="formData.transactionType = 'IN'"
            >
              借入
            </view>
          </view>
        </view>
        
        <!-- 其余表单项保持不变 -->
        <view class="form-item">
          <view class="form-label">金额</view>
          <input 
            type="digit" 
            v-model="formData.amount" 
            placeholder="请输入金额" 
            class="item-input"
          />
        </view>
        
        <!-- 账户类型选择 -->
        <view class="form-item" @tap="showAccountSelector">
          <view class="form-label">账户类型</view>
          <view class="item-value">
            <text class="account-value">{{ getAccountTypeText(formData.accountType) }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 日期选择 -->
        <view class="form-item" @tap="selectDate">
          <view class="form-label">借款日期</view>
          <view class="item-value">
            <text class="date-value">{{ formData.borrowDate }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 还款日期选择 -->
        <view class="form-item" @tap="selectRepaymentDate">
          <view class="form-label">还款日期</view>
          <view class="item-value">
            <text class="date-value">{{ formData.repaymentDate || '请选择' }}</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
        
        <!-- 备注输入 -->
        <view class="form-item">
          <view class="form-label">备注</view>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="item-textarea"
          />
        </view>

        <!-- 图片上传 -->
        <view class="form-item">
          <view class="form-label">相关凭证</view>
          <view class="image-uploader">
            <view class="image-list">
              <view 
                class="image-item" 
                v-for="(image, index) in imageList" 
                :key="index"
              >
                <image :src="image" mode="aspectFill" class="preview-image"></image>
                <view class="delete-btn" @tap="deleteImage(index)">×</view>
              </view>
              <view class="upload-btn" @tap="chooseImage" v-if="imageList.length < 9">
                <uni-icons type="plusempty" size="24" color="#999"></uni-icons>
                <text>上传图片</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 还款记录入口 -->
        <view class="form-item repayment-entry" v-if="!isAdd" @tap="viewRepaymentRecords">
          <view class="form-label">还款记录</view>
          <view class="item-value">
            <text class="repayment-text">查看还款记录</text>
            <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="bottom-bar" v-if="!isAdd">
        <view class="action-btn delete-btn" @tap="deleteRecord">删除</view>
        <view class="action-btn repay-all-btn" v-if="formData.status !== 2" @tap="setRepayAll">已还清</view>
        <view class="action-btn save-btn" @tap="saveRecord">保存</view>
      </view>
      
      <!-- 添加模式下的底部保存按钮 -->
      <view class="bottom-bar" v-if="isAdd">
        <view class="action-btn save-btn full-width" @tap="saveRecord">保存</view>
      </view>
      
      <!-- 日期选择器 -->
      <s-datetime-picker
        v-model:visible="showDatePicker"
        :initialDate="formData.borrowDate"
        mode="date"
        title="选择日期"
        @confirm="handleDateConfirm"
      />
      
      <!-- 还款日期选择器 -->
      <s-datetime-picker
        v-model:visible="showRepaymentDatePicker"
        :initialDate="formData.repaymentDate"
        mode="date"
        title="选择还款日期"
        @confirm="handleRepaymentDateConfirm"
      />
      
      <!-- 联系人选择器 -->
      <s-contact-selector
        v-model:visible="showContactSelector"
        title="选择联系人"
        :contacts="contactsList"
        :multiple="false"
        v-model="selectedContact"
        @confirm="handleContactConfirm"
      />
      
      <!-- 账户类型选择器 -->
      <s-dropdown-selector
        v-model:visible="accountSelectorVisible"
        title="选择账户类型"
        :options="accountOptions"
        v-model="selectedAccount"
        @confirm="handleAccountConfirm"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import sheep from '@/sheep';
import BorrowApi from '@/pages/money/api/borrow';
import FileApi from '@/sheep/api/infra/file';

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 页面参数
const isAdd = ref(true);
const recordId = ref(0);

// 账户类型相关
const accountSelectorVisible = ref(false);
const accountOptions = ref(['微信', '支付宝', '现金', '银行卡', '其他']);
const accountTypeMap = {
  '微信': 'WCHAT',
  '支付宝': 'ALIPAY',
  '现金': 'MONEY',
  '银行卡': 'BANK_CARD',
  '其他': 'OTHER'
};
const accountTypeReverseMap = {
  'WCHAT': '微信',
  'ALIPAY': '支付宝',
  'MONEY': '现金',
  'BANK_CARD': '银行卡',
  'OTHER': '其他'
};

// 表单数据
const formData = ref({
  id: null,
  borrowDate: formatDate(new Date()),
  repaymentDate: '',
  transactionType: 'OUT', // IN-收入，OUT-支出
  eventName: '',
  accountType: 'WCHAT', // 默认微信
  contactName: '',
  contactId: null,
  contactImg: '',
  status: 0, // 0-未还款，1-部分还清，2-已还清，3-已逾期
  amount: '',
  remark: '',
  imageUrls: null
});

// 图片列表
const imageList = ref([]);

// 联系人选择相关
const showContactSelector = ref(false);
const selectedContact = ref([]);
const contactsList = ref([]);

// 日期选择器相关状态
const showDatePicker = ref(false);
const showRepaymentDatePicker = ref(false);

// 获取姓名首字母
const getNameInitial = (name) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 页面加载时获取参数
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const params = currentPage.options || {};
  
  if (params.id) {
    isAdd.value = false;
    recordId.value = params.id;
    fetchRecordDetail(params.id);
  }
});

// 获取记录详情
const fetchRecordDetail = async (id) => {
  try {
    const response = await BorrowApi.queryBorrowRecordDetail({ id });
    
    if (response.code === 0 && response.data) {
      const record = response.data;
      formData.value = {
        id: record.id,
        borrowDate: formatDate(record.borrowDate),
        repaymentDate: record.repaymentDate ? formatDate(record.repaymentDate) : '',
        transactionType: record.transactionType,
        eventName: record.eventName || '',
        accountType: record.accountType || 'WCHAT',
        contactName: record.contactName,
        contactId: record.contactId,
        contactImg: record.contactImg || '',
        status: record.status,
        amount: record.amount,
        remark: record.remark || '',
        imageUrls: record.imageUrls
      };
      
      // 初始化图片列表
      if (record.imageUrls) {
        imageList.value = record.imageUrls.split(',');
      }
    } else {
      uni.showToast({
        title: response.msg || '获取记录详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取记录详情失败:', error);
    uni.showToast({
      title: '获取记录详情失败',
      icon: 'none'
    });
  }
};

// 选择联系人
const selectContact = () => {
  showContactSelector.value = true;
  
  // 设置当前选中的联系人
  if (formData.value.contactId) {
    selectedContact.value = [{
      id: formData.value.contactId,
      name: formData.value.contactName,
      avatar: formData.value.contactImg
    }];
  } else {
    selectedContact.value = [];
  }
};

// 处理联系人选择确认
const handleContactConfirm = (selected) => {
  if (selected.length > 0) {
    const contact = selected[0];
    formData.value.contactId = contact.id;
    formData.value.contactName = contact.name;
    formData.value.contactImg = contact.avatar;
  }
  showContactSelector.value = false;
};

// 选择日期
const selectDate = () => {
  showDatePicker.value = true;
};

// 处理日期选择确认
const handleDateConfirm = (result) => {
  if (result && result.date) {
    formData.value.borrowDate = result.date;
  }
};

// 选择还款日期
const selectRepaymentDate = () => {
  showRepaymentDatePicker.value = true;
};

// 处理还款日期选择确认
const handleRepaymentDateConfirm = (result) => {
  if (result && result.date) {
    formData.value.repaymentDate = result.date;
  }
};

// 选择图片
const chooseImage = async () => {
  uni.chooseImage({
    count: 9 - imageList.value.length,
    success: async (res) => {
      // 上传选中的图片
      for (const tempFilePath of res.tempFilePaths) {
        const result = await FileApi.uploadFile(tempFilePath);
        if (result && result.data) {
          imageList.value.push(result.data);
        }
      }
      // 更新 imageUrls
      formData.value.imageUrls = imageList.value.join(',');
    }
  });
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    urls: imageList.value,
    current: imageList.value[index]
  });
};

// 删除图片
const deleteImage = (index) => {
  imageList.value.splice(index, 1);
  formData.value.imageUrls = imageList.value.join(',');
};

// 显示账户选择器
const showAccountSelector = () => {
  accountSelectorVisible.value = true;
};

// 处理账户选择确认
const handleAccountConfirm = (selectedAccount) => {
  formData.value.accountType = accountTypeMap[selectedAccount] || 'OTHER';
};

// 获取账户类型文本
const getAccountTypeText = (type) => {
  return accountTypeReverseMap[type] || '请选择';
};

// 保存记录
const saveRecord = async () => {
  // 表单验证
  if (!formData.value.contactId) {
    uni.showToast({
      title: '请选择联系人',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.amount) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.borrowDate) {
    uni.showToast({
      title: '请选择借款日期',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    const params = {
      id: formData.value.id,
      borrowDate: formData.value.borrowDate,
      repaymentDate: formData.value.repaymentDate || null,
      transactionType: formData.value.transactionType,
      eventName: formData.value.eventName,
      accountType: formData.value.accountType,
      contactName: formData.value.contactName,
      contactId: formData.value.contactId,
      status: formData.value.status,
      amount: parseFloat(formData.value.amount),
      remark: formData.value.remark,
      imageUrls: formData.value.imageUrls
    };
    
    const response = await BorrowApi.addOrUpdateBorrowRecord(params);
    
    uni.hideLoading();
    
    if (response.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          // 设置需要刷新的标记
          uni.setStorageSync('borrowListNeedRefresh', true);
          // 跳转回借钱列表页面
          uni.redirectTo({
            url: '/pages/money/borrow-list'
          });
        }
      });
    } else {
      uni.showToast({
        title: response.msg || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存记录失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 移除不再需要的goBack方法
// const goBack = () => {
//   uni.navigateBack();
// };

// 查看还款记录
const viewRepaymentRecords = () => {
  sheep.$router.go('/pages/money/repayment-list', {
    borrowRecordId: formData.value.id
  });
};

// 设置已还清
const setRepayAll = () => {
  uni.showModal({
    title: '提示',
    content: '确定要将此借款记录标记为已还清吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '处理中...'
          });
          
          const response = await BorrowApi.repayAll({ id: Number(recordId.value) });
          
          uni.hideLoading();
          
          if (response.code === 0) {
            uni.showToast({
              title: '设置成功',
              icon: 'success',
              duration: 1500,
              success: () => {
                // 设置需要刷新的标记
                uni.setStorageSync('borrowListNeedRefresh', true);
                // 跳转回借钱列表页面
                uni.redirectTo({
                  url: '/pages/money/borrow-list'
                });
              }
            });
          } else {
            uni.showToast({
              title: response.msg || '设置失败',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('设置已还清失败:', error);
          uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 删除记录
const deleteRecord = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条借钱记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...'
          });
          
          const response = await BorrowApi.deleteBorrowRecord({ id: Number(recordId.value) });
          
          uni.hideLoading();
          
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 1500,
              success: () => {
                // 设置需要刷新的标记
                uni.setStorageSync('borrowListNeedRefresh', true);
                // 跳转回借钱列表页面
                uni.redirectTo({
                  url: '/pages/money/borrow-list'
                });
              }
            });
          } else {
            uni.showToast({
              title: response.msg || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          uni.hideLoading();
          console.error('删除记录失败:', error);
          uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
          });
        }
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.borrow-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 20rpx; /* 添加顶部间距 */
}

/* 移除原有的导航栏样式 */
.header {
  display: none;
}

.left, .right {
  display: none;
}

.title {
  display: none;
}

.form-container {
  padding: 0 0 120rpx; /* 修改顶部内边距 */
}

/* 其余样式保持不变 */
.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 2rpx;
  position: relative;
}

.contact-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
}

.contact-add {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.avatar-container {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  overflow: hidden;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #B388FF;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-name {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.form-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #333;
}

.type-selector {
  flex: 1;
  display: flex;
  border-radius: 8rpx;
  overflow: hidden;
  border: 1px solid #eee;
}

.type-item {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  
  &.active {
    background-color: #ff6b6b;
    color: #fff;
  }
}

.item-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.date-value {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.item-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

.item-textarea {
  flex: 1;
  height: 160rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

.image-uploader {
  flex: 1;
  margin-top: 20rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-item .delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  border-radius: 0 0 0 8rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 1px dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 24rpx;
  
  text {
    margin-top: 10rpx;
  }
}

.account-selector {
  flex: 1;
  display: flex;
  border-radius: 8rpx;
  overflow: hidden;
  border: 1px solid #eee;
}

.account-item {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  
  &.active {
    background-color: #ff6b6b;
    color: #fff;
  }
}

.account-value {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.input-field {
  width: 100%;
  height: 60rpx;
  font-size: 32rpx;
  color: #666;
  text-align: right;
}

.repayment-entry {
  margin-top: 20rpx;
  border-radius: 12rpx;
}

.repayment-text {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.action-btn {
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  width: 180rpx;
}

.bottom-bar .delete-btn {
  background-color: #fff;
  color: #ff6b6b;
  border: 1px solid #ff6b6b;
  margin-right: auto;
}

.bottom-bar .repay-all-btn {
  background-color: #fff;
  color: #4CAF50;
  border: 1px solid #4CAF50;
  margin: 0 20rpx;
}

.bottom-bar .save-btn {
  background-color: #007AFF;
  color: #fff;
}

.full-width {
  width: 100% !important;
  margin: 0 auto;
}
</style>